package com.iob.coin.covid19kg.dataset;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @Author: GuoXinyuan
 * @Date: 2021/5/29
 * jena jdbc driver操作封装
 */

public class JenaJdbcUtil {

    /**
     * 在给定datasource上执行sparql查询 主要用于封装异常处理逻辑
     * @param sparql 需要进行的sparql语句
     * @param dataSource 数据源
     */
    public static void query(String sparql,ResultSetHandler handler, DataSource dataSource) {

        Connection conn = null;
        Statement stmt = null;

        ResultSet resultSet;

        try {
            conn = dataSource.getConnection();
            stmt = conn.createStatement();

            resultSet = stmt.executeQuery(sparql);

            handler.handle(resultSet);

        } catch (SQLException sqlException){
            sqlException.printStackTrace();
        } finally {
            try {
                assert conn != null;
                conn.close();
            } catch (SQLException sqlException){
                sqlException.printStackTrace();
            } finally {
                try {
                    assert stmt != null;
                    stmt.close();
                } catch (SQLException sqlException){
                    sqlException.printStackTrace();
                }
            }
        }
    }

    /**
     * 用于处理结果集的函数式接口
     * 结果集如果作为返回值传递无法调用next()获取结果
     */
    @FunctionalInterface
    public interface ResultSetHandler{
        void handle(ResultSet resultSet) throws SQLException;
    }


}
